﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PMS
{
    public class Permission
    {
        #region 1.0 根据用户Id，获取用户所有的查看权限
        /// <summary>
        /// 根据用户Id，获取用户所有的查看权限
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static List<BD_Permission> GetPermByUserId(int Id)
        {
            //-------A.根据用户角色查询
            //1.0 根据用户 id 查到 该用户的 角色id
            List<int> listRoleId = DALSession.Current.BD_UserRoleDAL.GetListBy(ur => ur.UId == Id).Select(ur => ur.RId).ToList();
            //2.0 根据角色 id 查询角色权限 id
            List<int> listPerIds = DALSession.Current.BD_RolePermissionDAL.GetListBy(rp => listRoleId.Contains(rp.RId)).Select(rp => rp.PId).ToList();
            //3.0 查询所有角色数据
            List<BD_Permission> listPermission = DALSession.Current.BD_PermissionDAL.GetListBy(p => listPerIds.Contains(p.Id)).ToList();
            //-------B.根据用户特权查询
            //b.1 查询 用户特权id
            List<int> vipPerIds = DALSession.Current.BD_UserVipPermissionDAL.GetListBy(vip => vip.vipUserId == Id).Select(vip => vip.vipPermission).ToList();
            //b.2 查询 特权数据
            List<BD_Permission> listPermission2 = DALSession.Current.BD_PermissionDAL.GetListBy(p => vipPerIds.Contains(p.Id)).ToList();
            //-------C.将两个权限集合 合并（将集合2的权限数据 添加到 集合1中）
            listPermission2.ForEach(p =>
            {
                if (!listPerIds.Contains(p.Id))
                {
                    listPermission.Add(p);
                }

            });
            return listPermission.OrderBy(u => u.OrderField).ToList();
        }
        #endregion

        #region 2.0根据权限集合创建树节点权限

        /// <summary>
        /// 根据权限集合创建树节点权限
        /// </summary>
        /// <param name="per"></param>
        /// <returns></returns>
        public static List<TreeNode> GetPerTree(List<BD_Permission> listPer)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            var showList = listPer.Where(p => p.IsShow == "0").ToList();
            LoadTreeNode(showList, listNodes, 0);
            return listNodes;
        }


        #endregion

        #region 3.0 递归创建树节点集合
        /// <summary>
        /// 递归创建 树节点集合
        /// </summary>
        /// <param name="listPer">权限集合</param>
        /// <param name="listNodes">树点集合</param>
        /// <param name="pid"></param>
        public static void LoadTreeNode(List<BD_Permission> listPer, List<TreeNode> listNodes, int pid)
        {
            foreach (var permission in listPer)
            {
                if (permission.Parent == pid)
                {
                    //将 权限转成 树节点
                    TreeNode node = new TreeNode()
                    {
                        id = permission.Id,
                        text = permission.Name,
                        iconCls = permission.Ico,
                        Checked = false,
                        attributes = new { url = permission.LinkUrl },
                        children = new List<TreeNode>()
                    };
                    if (listPer.Count(p => p.Parent == permission.Id) > 0)
                    {
                        node.state = "closed";
                    }
                    else
                    {
                        node.state = "open";
                    }
                    listNodes.Add(node);
                    LoadTreeNode(listPer, node.children, node.id);
                }
            }
        }
        #endregion

        #region 4.0 根据用户Id，获取用户所有的按钮权限
        /// <summary>
        /// 根据用户Id，获取用户所有的按钮权限
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static List<BD_btnPermission> GetBtnPermByUserId(int Id)
        {
            //-------A.根据用户角色查询
            //1.0 根据用户 id 查到 该用户的 角色id
            List<int> listRoleId = DALSession.Current.BD_UserRoleDAL.GetListBy(ur => ur.UId == Id).Select(ur => ur.RId).ToList();
            //2.0 根据角色 id 查询角色按钮权限 id
            List<int> listbtnPerIds = DALSession.Current.BD_RoleBtnPermissionDAL.GetListBy(rp => listRoleId.Contains(rp.RId)).Select(rp => rp.BId).ToList();
            //3.0 查询所有角色按钮数据
            List<BD_btnPermission> listPermission = DALSession.Current.BD_btnPermissionDAL.GetListBy(p => listbtnPerIds.Contains(p.Id)).ToList();
            //-------B.根据用户特权查询
            //b.1 查询 用户特权id
            List<int> vipPerIds = DALSession.Current.BD_UserVipBtnPermissionDAL.GetListBy(vip => vip.vipUserId == Id).Select(vip => vip.vipBtnPermission).ToList();
            //b.2 查询 特权数据
            List<BD_btnPermission> listPermission2 = DALSession.Current.BD_btnPermissionDAL.GetListBy(p => vipPerIds.Contains(p.Id)).ToList();
            //-------C.将两个权限集合 合并（将集合2的权限数据 添加到 集合1中）
            listPermission2.ForEach(p =>
            {
                if (!listbtnPerIds.Contains(p.Id))
                {
                    listPermission.Add(p);
                }

            });
            return listPermission.OrderBy(u => u.Id).ToList();
        }
        #endregion


        #region 5.0 获取系统所有权限
        /// <summary>
        /// 获取系统所有权限
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static List<BD_Permission> GetAllPerm()
        {

            List<BD_Permission> listPermission = DALSession.Current.BD_PermissionDAL.GetListBy(p => 1 == 1).ToList();

            return listPermission.OrderBy(u => u.OrderField).ToList();
        }
        #endregion



        #region 6.0根据总权限和部分权限创建带勾选项的树

        /// <summary>
        /// 根据总权限和部分权限创建带勾选项的树
        /// </summary>
        /// <param name="per"></param>
        /// <returns></returns>
        public static List<BD_Permission> GetPerTreeBySubTree(List<BD_Permission> listPer, List<int> subListPer, List<BD_btnPermission> allBtnList, List<int> thisBtnIdList)
        {
            List<BD_Permission> listNodes = new List<BD_Permission>();
            LoadTreeNodeBySubTree(listPer, listNodes, 0, subListPer, allBtnList, thisBtnIdList);
            return listNodes;
        }


        #endregion

        #region 7.0 递归创建树节点集合
        /// <summary>
        /// 递归创建 树节点集合
        /// </summary>
        /// <param name="listPer">权限集合</param>
        /// <param name="listNodes">树点集合</param>
        /// <param name="pid"></param>
        public static void LoadTreeNodeBySubTree(List<BD_Permission> listPer, List<BD_Permission> listNodes, int pid, List<int> subPer, List<BD_btnPermission> allBtnList, List<int> thisBtnIdList)
        {
            var subPerList = listPer.Where(p => p.Parent == pid).OrderBy(p => p.OrderField).ToList();
            foreach (var permission in subPerList)
            {
                if (permission.Parent == pid)
                {
                    //将 权限转成 树节点
                    BD_Permission node = new BD_Permission()
                    {
                        Id = permission.Id,
                        Ico = permission.Ico,
                        IsFatherNode = permission.IsFatherNode,
                        IsShortCut = permission.IsShortCut,
                        IsShow = permission.IsShow,
                        LinkUrl = permission.LinkUrl,
                        Name = permission.Name,
                        Note = permission.Note,
                        OrderField = permission.OrderField,
                        Parent = permission.Parent,
                        ShortCutPic = permission.ShortCutPic,
                       
                        Checked = false,
                        children = new List<BD_Permission>()
                    };
                    if (permission.IsFatherNode=="0")
                    {
                        permission.state = "closed";
                    }
                    else
                    {
                        permission.state = "open";
                    }
                    var btnPerList = allBtnList.Where(b => b.perId == permission.Id).OrderBy(b => b.Order).ToList();
                    if (btnPerList.Count > 0)
                    {
                        foreach (var subBtn in btnPerList)
                        {
                            if (thisBtnIdList.Contains(subBtn.Id))
                            {
                                subBtn.Checked = true;
                            }
                        }
                        node.btn = btnPerList;
                    }
                    if (subPer.Contains(permission.Id))
                    {
                        node.Checked = true;
                    }
                    listNodes.Add(node);
                    LoadTreeNodeBySubTree(listPer, node.children, node.Id, subPer, allBtnList, thisBtnIdList);
                }
            }
        }
        #endregion

        public static List<BD_Permission> GetPermByRole(int roleId)
        {
            List<int> listPId =
DALSession.Current.BD_RolePermissionDAL.GetListBy(r => r.RId == roleId).Select(r => r.PId).ToList();
            return DALSession.Current.BD_PermissionDAL.GetListBy(p => listPId.Contains(p.Id));
        }

        //获取所有角色
        public static List<BD_Role> GetAllRole(int roleId)
        {

            List<BD_Role> listRole = DALSession.Current.BD_RoleDAL.GetListBy(p => 1 == 1).ToList();
            return listRole.OrderBy(u => u.Id).ToList();
        }

        //获取角色的所有权限页面，不包括一级页面
        public static List<BD_Permission> GetPermByRoleEr(int roleId)
        {
            List<int> listPId = DALSession.Current.BD_RolePermissionDAL.GetListBy(r => r.RId == roleId).Select(r => r.PId).ToList();
            return DALSession.Current.BD_PermissionDAL.GetListBy(p => listPId.Contains(p.Id) && p.Parent != 0);
        }

        //获取所有权限页面（不包括一级)的按钮
        public static List<BD_btnPermission> GetAllBtnPerm(List<BD_Permission> perList)
        {
            List<int> perIdList = perList.Select(p => p.Id).ToList();
            return DALSession.Current.BD_btnPermissionDAL.GetListBy(p => perIdList.Contains(p.perId));
        }

        //获取所有权限页面（不包括一级)的按钮
        public static List<int> GetBtnPermIdListByRole(int roleId)
        {
            return DALSession.Current.BD_RoleBtnPermissionDAL.GetListBy(r => r.RId == roleId).Select(r => r.BId).ToList();

        }



        #region //创建按钮的树节点Role
        public static List<TreeNode> GetBtnTree(List<BD_Permission> listPer, List<BD_btnPermission> subListPer, List<int> btnCheckIdlist)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            foreach (var per in listPer)
            {
                TreeNode node = new TreeNode() { id = per.Id, text = per.Name, state = "closed", Checked = true };
                listNodes.Add(node);
                LoadTreeNodeBySubTreeAnniu(node, subListPer, btnCheckIdlist);
            }
            return listNodes;
        }


        public static void LoadTreeNodeBySubTreeAnniu(TreeNode Node, List<BD_btnPermission> subListPer, List<int> btnCheckIdlist)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            List<BD_btnPermission> sub = subListPer.Where(s => s.perId == Node.id).ToList();
            foreach (var s in sub)
            {
                if (btnCheckIdlist.Contains(s.Id))
                {
                    listNodes.Add(new TreeNode() { id = s.Id, text = s.Name, Checked = true });
                }
                else
                {
                    listNodes.Add(new TreeNode() { id = s.Id, text = s.Name, Checked = false });
                }
            }
            Node.children = listNodes;

        }
        #endregion

        //获取所有页面
        public static List<BD_Permission> GetAllLink()
        {

            List<BD_Permission> listLink = DALSession.Current.BD_PermissionDAL.GetListBy(p => 1 == 1).ToList();
            return listLink.OrderBy(u => u.Id).ToList();
        }
        #region 根据用户id获取相应页面
        //根据用户id获取相应页面
        public static List<BD_UserVipPermission> GetPermByUserid(int userId)
        {
            List<int> userPId =
DALSession.Current.BD_UserVipPermissionDAL.GetListBy(r => r.vipUserId == userId).Select(r => r.vipPermission).ToList();
            return DALSession.Current.BD_UserVipPermissionDAL.GetListBy(p => userPId.Contains(p.vipPermission));
        }
        public static List<TreeNode> GetPerTreeBySubTreeUserid(List<BD_Permission> listPer, List<BD_UserVipPermission> subListPer)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            LoadTreeNodeBySubTreeUserid(listPer, listNodes, 0, subListPer);
            return listNodes;
        }
        public static void LoadTreeNodeBySubTreeUserid(List<BD_Permission> listPer, List<TreeNode> listNodes, int pid, List<BD_UserVipPermission> subListPer)
        {
            foreach (var permission in listPer)
            {
                if (permission.Parent == pid)
                {
                    //将 页面链接转成 树节点
                    TreeNode node = new TreeNode()
                    {
                        id = permission.Id,
                        text = permission.Name,
                        state = "open",
                        Checked = false,
                        attributes = new { url = permission.LinkUrl },
                        children = new List<TreeNode>()
                    };
                    if (subListPer.Count(p => p.vipPermission == permission.Id) > 0)
                    {
                        node.Checked = true;
                    }
                    listNodes.Add(node);
                    LoadTreeNodeBySubTreeUserid(listPer, node.children, node.id, subListPer);
                }
            }
        }
        #endregion

        #region 根据用户分配特殊按钮权限
        public static List<BD_Permission> GetPermByUserEr(int userId)
        {
            List<int> listPId = DALSession.Current.BD_UserVipPermissionDAL.GetListBy(u => u.vipUserId == userId).Select(u => u.vipPermission).ToList();
            return DALSession.Current.BD_PermissionDAL.GetListBy(p => listPId.Contains(p.Id) && p.Parent != 0);
        }
        public static List<BD_btnPermission> GetAllBtnPermUser(List<BD_Permission> perList)
        {
            List<int> perIdList = perList.Select(p => p.Id).ToList();
            return DALSession.Current.BD_btnPermissionDAL.GetListBy(p => perIdList.Contains(p.perId));
        }
        public static List<int> GetBtnPermIdListByUserid(int userId)
        {
            return DALSession.Current.BD_UserVipBtnPermissionDAL.GetListBy(r => r.vipUserId == userId).Select(r => r.vipBtnPermission).ToList();

        }
        //创建按钮的树节点ByUser
        public static List<TreeNode> GetBtnTreeUser(List<BD_Permission> listPer, List<BD_btnPermission> subListPer, List<int> btnCheckIdlist)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            foreach (var per in listPer)
            {
                TreeNode node = new TreeNode() { id = per.Id, text = per.Name, state = "closed", Checked = true };
                listNodes.Add(node);
                LoadTreeNodeBySubTreeBtnUser(node, subListPer, btnCheckIdlist);
            }
            return listNodes;
        }


        public static void LoadTreeNodeBySubTreeBtnUser(TreeNode Node, List<BD_btnPermission> subListPer, List<int> btnCheckIdlist)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            List<BD_btnPermission> sub = subListPer.Where(s => s.perId == Node.id).ToList();
            foreach (var s in sub)
            {
                if (btnCheckIdlist.Contains(s.Id))
                {
                    listNodes.Add(new TreeNode() { id = s.Id, text = s.Name, Checked = true });
                }
                else
                {
                    listNodes.Add(new TreeNode() { id = s.Id, text = s.Name, Checked = false });
                }
            }
            Node.children = listNodes;

        }
        #endregion


        /// <summary>
        /// //获取本人快捷登录权限
        /// </summary>
        /// <returns></returns>
        public static List<BD_Permission> GetShortCutByMe()
        {
            List<int> list = DALSession.Current.BD_UserShortCutDAL.GetListBy(u => u.uId == OperateContext.SessBasicInfo.UserInfo.Id).Select(u => u.pId).ToList();
            return DALSession.Current.BD_PermissionDAL.GetListBy(p => list.Contains(p.Id)).ToList();
        }
    }
}